# coding=utf-8
# 代码文件：chapter2/ch2.6.py
import time

import cv2
import pytesseract as tess
from PIL import Image
from selenium import webdriver

''' 验证码识别函数，参数是要识别的图片路径 '''


def identifycode(imagefilePath):
    # 1.读取图片 读imread函数是OpnCV库提供
    src_image = cv2.imread(imagefilePath)
    # 2.转为灰度化图像
    gray_image = cv2.cvtColor(src_image, cv2.COLOR_BGR2GRAY)
    # 3.转为二值化图像
    th_image = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 21, 2)

    pil_image = Image.fromarray(th_image)
    # 转文本显示
    text = tess.image_to_string(pil_image)

    vcode = text.strip().replace(' ', '')  # 删除字符串前后空白，并替换字符串中的空格

    return vcode


if __name__ == '__main__':
    # 要识别的图片
    fileimg = './captcha_img/test1.png'

    vcode = identifycode(fileimg)
    print(vcode)
